﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm_Mes
{
 

    public partial class LoginForm : DevExpress.XtraEditors.XtraForm
    {
    
        public LoginForm()
        {
            InitializeComponent();
            btnLogin.Click += btnLogin_Click;
        }

        private async void btnLogin_Click(object sender, EventArgs e)
        {
            var loginRequest = new
            {
                UserName = txtUsername.Text,
                Password = txtPassword.Text
            };

            try
            {
                using (var client = new HttpClient())
                {
                    // 现在 PostAsJsonAsync 不会报错了
                    var response = await client.PostAsJsonAsync("http://localhost:5078/api/User/Login", loginRequest);

                    if (response.IsSuccessStatusCode)
                    {
                        // 将JSON响应反序列化为我们定义的LoginResponse对象
                        var result = await response.Content.ReadFromJsonAsync<LoginResponse>();
                        if (result != null && result.code == 200)
                        {
                            this.DialogResult = DialogResult.OK;
                            this.Close();
                        }
                        else
                        {
                            XtraMessageBox.Show(result?.message ?? "返回的响应格式不正确。", "登录失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("登录请求失败，请检查网络或联系管理员。", "网络错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("发生未知错误：" + ex.Message, "严重错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public class LoginResponse
        {
            public int code { get; set; }
            public string message { get; set; }
        }
    }
}